﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Model.Extend.Models;
using Estsh.Core.Models;
using Estsh.Core.Repositories;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Wms.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Estsh.Core.Model.EnumUtil.WmsEnumUtil;

namespace Estsh.Core.Wms.Repositories
{
    public class FinishShippingRepository:BaseRepository<BaseEntity>, IFinishShippingRepository
    {
        public FinishShippingRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {
        }

        /// <summary>
        /// 生成订单编号
        /// </summary>
        /// <returns></returns>
        private string GetOrderNo(string stockOrder, string p)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                DynamicParameters list = new DynamicParameters();
                list.Add("@order_type", stockOrder);
                list.Add("@order_prefix", p);
                list.Add("@order_no", null, DbType.String, ParameterDirection.Output, 50);

                var hashtable = dbConn.Execute("sys_create_orderno", list, commandType: CommandType.StoredProcedure);// this._remotingProxy.ExecuteSotreProcedure("dbo.sys_create_orderno", list);
                string result = list.Get<string>("@order_no");
                return result;
            }
        }

        public List<WmsOutstock_Extend> GetWmsOutstocks(string orderno)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("SELECT * FROM dbo.wms_outstock (nolock) WHERE order_type=120 AND order_status=10 AND enabled='Y'");
                if (!string.IsNullOrEmpty(orderno))
                {
                    sql.Append($" AND order_no LIKE '%{orderno}%'");
                }

                return dbConn.Query<WmsOutstock_Extend>(sql.ToString()).ToList();
            }
        }

        public List<WmsOutstockDetail> GetWmsOutstockDetail(string orderno,int status)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"SELECT * FROM dbo.wms_outstock_detail (nolock) WHERE order_no='{orderno}' AND enabled='Y'");
                if (status != 40)
                {
                    sql.Append(" AND item_status IN (10,20,30,40)");
                }
                else
                {
                    sql.Append(" AND item_status=40");
                }

                return dbConn.Query<WmsOutstockDetail>(sql.ToString()).ToList();
            }
        }

        public List<SysStock> GetSysStocks(string orderno,int status)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                if (status == 50)
                {
                    sql.Append($"SELECT * FROM dbo.sys_stock (nolock) WHERE carton_no='{orderno}' and status={status} AND enabled='Y'");

                }
                if (status == 100)
                {
                    sql.Append($"SELECT * FROM dbo.sys_stock (nolock) WHERE carton_no='{orderno}' and status={status} AND enabled='Y'");

                }
                return dbConn.Query<SysStock>(sql.ToString()).ToList();
            }
        }

        public List<SysStock> GetQtys(string cartonNo,int qty)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"SELECT * FROM dbo.sys_stock (nolock) WHERE carton_no='{cartonNo}' and qty={qty} AND enabled='Y'");

                return dbConn.Query<SysStock>(sql.ToString()).ToList();
            }
        }

        public string AddRackPackage(string cartonNo,int loginid,string shippingNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                #region  wms_rack_package
                List<string> sqlList = new List<string>();
                List<DynamicParameters> parametersList = new List<DynamicParameters>();
                DynamicParameters parameters = new DynamicParameters();
                string result = string.Empty;
                List<SysStock> sysStocks= GetSysStocks(cartonNo,50);//获取箱标签信息
                //获取工厂信息
                StringBuilder builder= new StringBuilder(1024);
                builder.Append("SELECT * FROM dbo.sys_factory WHERE enabled='Y'");
                List<SysFactory> factories = dbConn.Query<SysFactory>(builder.ToString()).ToList();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("INSERT INTO dbo.wms_rack_package (rack_no,corton_no,packageType,part_no,");
                sql.Append(" rack_num,factory_id,factory_code,enabled,create_userid,create_time)");
                sql.Append("VALUES (@rackNo,@cortonNo,@packageType,@partNo,@rackNum,@factoryId,");
                sql.Append(" @factoryCode,@enabled,@createUserid,@createTime)");

                sqlList.Add(sql.ToString());
                
                parameters.Add("@rackNo", "");
                parameters.Add("@cortonNo", cartonNo);
                parameters.Add("@packageType", 2);
                parameters.Add("@partNo", sysStocks.FirstOrDefault().PartNo);
                parameters.Add("@rackNum", sysStocks.FirstOrDefault().Qty);
                parameters.Add("@factoryId", factories.FirstOrDefault().FactoryId);
                parameters.Add("@factoryCode", factories.FirstOrDefault().FactoryCode);
                parameters.Add("@enabled", 'Y');
                parameters.Add("@createUserid", loginid);
                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                parametersList.Add(parameters);

                ExecuteTransaction(sqlList, parametersList);
                #endregion

                #region  shipping_log
                List<string> sqlLists = new List<string>();
                List<DynamicParameters> parametersLists = new List<DynamicParameters>();
                DynamicParameters dynamics = new DynamicParameters();
                //获取物流公司信息
                StringBuilder stringBuilder = new StringBuilder(1024);
                stringBuilder.Append($"SELECT * FROM dbo.wms_outstock WHERE order_no='{shippingNo}'");
                List<WmsOutstock_Extend> wmsOutstocks = dbConn.Query<WmsOutstock_Extend>(stringBuilder.ToString()).ToList();

                StringBuilder builder1 = new StringBuilder(1024);
                builder1.Append("INSERT INTO dbo.sys_shipping_log (shipping_no,part_no,rack_no,carton_no,");
                builder1.Append(" qty,logistics_code,box_weight,all_cost,shipping_type,");
                builder1.Append(" factory_id,factory_code,enabled,create_userid,create_time)");
                builder1.Append("VALUES (@shippingNo,@partNo,@rackNo,@cartonNo,");
                builder1.Append(" @qty,@logisticsCode,@boxWeight,@allCost,@shippingType,");
                builder1.Append(" @factoryId,@factoryCode,@enabled,@createUserid,@createTime)");

                sqlLists.Add(builder1.ToString());

                dynamics.Add("@shippingNo", shippingNo);
                dynamics.Add("@partNo", sysStocks.FirstOrDefault().PartNo);
                dynamics.Add("@qty", sysStocks.FirstOrDefault().Qty);
                dynamics.Add("@rackNo", "");
                dynamics.Add("@cartonNo", cartonNo);
                dynamics.Add("@logisticsCode", wmsOutstocks.FirstOrDefault().LogisticsCompany);
                dynamics.Add("@boxWeight", 0);
                dynamics.Add("@allCost", 0);
                dynamics.Add("@shippingType", 1);
                dynamics.Add("@factoryId", factories.FirstOrDefault().FactoryId);
                dynamics.Add("@factoryCode", factories.FirstOrDefault().FactoryCode);
                dynamics.Add("@enabled", 'Y');
                dynamics.Add("@createUserid", loginid);
                dynamics.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                parametersLists.Add(dynamics);

                ExecuteTransaction(sqlLists, parametersLists);
                #endregion

                return result;
            }
        }


        public int UpdateStatusAndLocate(string cartonNo,string orderNo,int qty,int loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder builder = new StringBuilder(1024);
                builder.Append($"SELECT * FROM dbo.sys_stock (nolock) WHERE carton_no='{cartonNo}' AND enabled='Y'");
                List<SysStock> sysStocks=dbConn.Query<SysStock>(builder.ToString()).ToList();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"UPDATE dbo.sys_stock SET status=100,locate_id=0,locate_name='',relevance_order='{orderNo}',update_userid={loginId},update_time=GETDATE() WHERE carton_no='{cartonNo}' AND enabled='Y';");

                StringBuilder stringBuilder= new StringBuilder(1024);
                stringBuilder.Append($"SELECT * FROM dbo.wms_outstock_detail (nolock) WHERE order_no='{orderNo}' AND part_no='{sysStocks.FirstOrDefault().PartNo}' AND enabled='Y'");
                List<WmsOutstockDetail> details = dbConn.Query<WmsOutstockDetail>(stringBuilder.ToString()).ToList();
                if (details.FirstOrDefault().Qty == details.FirstOrDefault().OutQty + qty)
                {
                    sql.Append($"UPDATE dbo.wms_outstock_detail SET item_status=40, out_qty=out_qty+{qty},update_userid={loginId},update_time=GETDATE(),src_locate_id=0,src_locate_name='' WHERE order_no='{orderNo}' AND part_no='{sysStocks.FirstOrDefault().PartNo}' AND enabled='Y'");

                }
                if (details.FirstOrDefault().Qty < details.FirstOrDefault().OutQty + qty)
                {
                    return -1;
                }
                if (details.FirstOrDefault().Qty > details.FirstOrDefault().OutQty + qty)
                {
                    sql.Append($"UPDATE dbo.wms_outstock_detail SET out_qty=out_qty+{qty},update_userid={loginId},update_time=GETDATE(),src_locate_id=0,src_locate_name='' WHERE order_no='{orderNo}' AND part_no='{sysStocks.FirstOrDefault().PartNo}' AND enabled='Y'");

                }

                return dbConn.Execute(sql.ToString());
            }
        }

        public List<SysStock> CheckMaterialSplit(List<SysStock> oldStock, int splitNum, string loginId, int splitCount, string shippingNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                //获取物流公司信息
                StringBuilder stringBuilder = new StringBuilder(1024);
                stringBuilder.Append($"SELECT * FROM dbo.wms_outstock (nolock) WHERE order_no='{shippingNo}' AND enabled='Y'");
                List<WmsOutstock_Extend> wmsOutstocks = dbConn.Query<WmsOutstock_Extend>(stringBuilder.ToString()).ToList();

                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();

                decimal oldQty = oldStock[0].Qty;
                decimal newQty = oldStock[0].Qty - splitNum;

                //更新条码表，数量
                StringBuilder updateString = new StringBuilder(1024);
                updateString.Append("update sys_stock set qty=@qty, update_userid=@update_userid,update_time=@update_time where carton_no=@carton_no ");
                DynamicParameters updateStringparameters = new DynamicParameters();
                updateStringparameters.Add("@qty", newQty);
                updateStringparameters.Add("@carton_no", oldStock[0].CartonNo);
                updateStringparameters.Add("@update_userid", loginId);
                updateStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStrings.Add(updateString.ToString());
                parameterList.Add(updateStringparameters);


                //新增 sys_stock_trans 事务表
                #region sys_stock_trans 事务表

                StringBuilder updateString4 = new StringBuilder(1024);
                updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                DynamicParameters updateStringparameters4 = new DynamicParameters();
                updateStringparameters4.Add("@trans_code", (int)TransType.PART_SPLIT);
                updateStringparameters4.Add("@carton_no", oldStock[0].CartonNo);
                updateStringparameters4.Add("@part_id", oldStock[0].PartId);
                updateStringparameters4.Add("@part_no", oldStock[0].PartNo);
                updateStringparameters4.Add("@part_spec", oldStock[0].PartSpec);
                updateStringparameters4.Add("@src_locate_id", oldStock[0].LocateId);
                updateStringparameters4.Add("@src_locate_name", oldStock[0].LocateName);
                updateStringparameters4.Add("@dest_locate_id", oldStock[0].LocateId);
                updateStringparameters4.Add("@dest_locate_name", oldStock[0].LocateName);
                updateStringparameters4.Add("@old_qty", oldQty);
                updateStringparameters4.Add("@new_qty", newQty);
                updateStringparameters4.Add("@trans_qty", oldStock[0].Qty);
                updateStringparameters4.Add("@old_status", oldStock[0].Status);
                updateStringparameters4.Add("@new_status", oldStock[0].Status);
                updateStringparameters4.Add("@old_qms_status", oldStock[0].QmsStatus);
                updateStringparameters4.Add("@new_qms_status", oldStock[0].QmsStatus);
                updateStringparameters4.Add("@unit", oldStock[0].Unit);
                updateStringparameters4.Add("@factory_id", oldStock[0].FactoryId);
                updateStringparameters4.Add("@factory_code", oldStock[0].FactoryCode);
                updateStringparameters4.Add("@src_erp_warehouse", oldStock[0].ErpWarehouse);
                updateStringparameters4.Add("@dest_erp_warehouse", oldStock[0].ErpWarehouse);
                updateStringparameters4.Add("@src_warehouse_id", oldStock[0].WarehouseId);
                updateStringparameters4.Add("@src_warehouse_name", oldStock[0].WarehouseName);
                updateStringparameters4.Add("@dest_warehouse_id", oldStock[0].WarehouseId);
                updateStringparameters4.Add("@dest_warehouse_name", oldStock[0].WarehouseName);
                updateStringparameters4.Add("@src_zone_id", oldStock[0].ZoneId);
                updateStringparameters4.Add("@src_zone_name", oldStock[0].ZoneName);
                updateStringparameters4.Add("@dest_zone_id", oldStock[0].ZoneId);
                updateStringparameters4.Add("@dest_zone_name", oldStock[0].ZoneName);
                updateStringparameters4.Add("@enabled", oldStock[0].Enabled);
                updateStringparameters4.Add("@update_userid", loginId);
                updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters4.Add("@create_userid", loginId);
                updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters4.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(updateString4.ToString());
                parameterList.Add(updateStringparameters4);
                #endregion

                oldStock[0].CartonNo = checkCartonNo(oldStock[0].CartonNo, splitCount);

                oldStock[0].Qty = splitNum;
                //插入拆分出的箱条码
                #region 插入拆分出的箱条码

                StringBuilder updateString3 = new StringBuilder(1024);
                updateString3.Append(@" INSERT INTO [dbo].[sys_stock]
                                        ([vendor_id]
                                        ,[vendor_code]
                                        ,[carton_no]
                                        ,[part_id]
                                        ,[part_no]
                                        ,[part_spec]
                                        ,[lot_no]
                                        ,[fix_lot_no]
                                        ,[status]
                                        ,[qty]
                                        ,[snp_qty]
                                        ,[locate_id]
                                        ,[locate_name]
                                        ,[group_no]
                                        ,[erp_warehouse]
                                        ,[date_code]
                                        ,[qms_status]
                                        ,[ref_order_no]
                                        ,[unit]
                                        ,[dock]
                                        ,[warehouse_id]
                                        ,[warehouse_name]
                                        ,[zone_id]
                                        ,[zone_name]
                                        ,[printed]
                                        ,[print_time]
                                        ,[remark]
                                        ,[factory_id]
                                        ,[factory_code]
                                        ,[enabled]
                                        ,[create_userid]
                                        ,[create_time]
                                        ,[update_userid]
                                        ,[update_time]
                                        ,[guid])
                                        VALUES(@vendor_id,@vendor_code,@carton_no,@part_id,@part_no,@part_spec,@lot_no,@fix_lot_no,@status,@qty,@snp_qty
,@locate_id,@locate_name,@group_no,@erp_warehouse,@date_code,@qms_status,@ref_order_no,@unit,@dock,@warehouse_id,@warehouse_name,@zone_id,@zone_name
,@printed,@print_time,@remark,@factory_id,@factory_code,@enabled,@create_userid,@create_time,@update_userid,@update_time,@guid )");

                DynamicParameters updateStringparameters3 = new DynamicParameters();
                updateStringparameters3.Add("@vendor_id", oldStock[0].VendorId);
                updateStringparameters3.Add("@vendor_code", oldStock[0].VendorCode);
                updateStringparameters3.Add("@carton_no", oldStock[0].CartonNo);
                updateStringparameters3.Add("@part_id", oldStock[0].PartId);
                updateStringparameters3.Add("@part_no", oldStock[0].PartNo);
                updateStringparameters3.Add("@part_spec", oldStock[0].PartSpec);
                updateStringparameters3.Add("@lot_no", oldStock[0].LotNo);
                updateStringparameters3.Add("@fix_lot_no", oldStock[0].FixLotNo);
                updateStringparameters3.Add("@status", 100);
                updateStringparameters3.Add("@qty", splitNum);
                updateStringparameters3.Add("@snp_qty", oldStock[0].SnpQty);
                updateStringparameters3.Add("@locate_id", oldStock[0].LocateId);
                updateStringparameters3.Add("@locate_name", oldStock[0].LocateName);
                updateStringparameters3.Add("@group_no", oldStock[0].GroupNo);
                updateStringparameters3.Add("@erp_warehouse", oldStock[0].ErpWarehouse);
                updateStringparameters3.Add("@date_code", oldStock[0].DateCode);
                updateStringparameters3.Add("@qms_status", oldStock[0].QmsStatus);
                updateStringparameters3.Add("@ref_order_no", oldStock[0].RefOrderNo);
                updateStringparameters3.Add("@unit", oldStock[0].Unit);
                updateStringparameters3.Add("@dock", oldStock[0].Dock);
                updateStringparameters3.Add("@warehouse_id", oldStock[0].WarehouseId);
                updateStringparameters3.Add("@warehouse_name", oldStock[0].WarehouseName);
                updateStringparameters3.Add("@zone_id", oldStock[0].ZoneId);
                updateStringparameters3.Add("@zone_name", oldStock[0].ZoneName);
                updateStringparameters3.Add("@printed", oldStock[0].Printed);
                updateStringparameters3.Add("@print_time", oldStock[0].PrintTime);
                updateStringparameters3.Add("@remark", oldStock[0].Remark);
                updateStringparameters3.Add("@factory_id", oldStock[0].FactoryId);
                updateStringparameters3.Add("@factory_code", oldStock[0].FactoryCode);
                updateStringparameters3.Add("@enabled", oldStock[0].Enabled);
                updateStringparameters3.Add("@update_userid", loginId);
                updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters3.Add("@create_userid", loginId);
                updateStringparameters3.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters3.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(updateString3.ToString());
                parameterList.Add(updateStringparameters3);
                #endregion

                //新增 sys_stock_trans 事务表
                #region sys_stock_trans 事务表

                StringBuilder updateString5 = new StringBuilder(1024);
                updateString5.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                DynamicParameters updateStringparameters5 = new DynamicParameters();
                updateStringparameters5.Add("@trans_code", (int)TransType.PART_SPLIT);
                updateStringparameters5.Add("@carton_no", oldStock[0].CartonNo);
                updateStringparameters5.Add("@part_id", oldStock[0].PartId);
                updateStringparameters5.Add("@part_no", oldStock[0].PartNo);
                updateStringparameters5.Add("@part_spec", oldStock[0].PartSpec);
                updateStringparameters5.Add("@src_locate_id", oldStock[0].LocateId);
                updateStringparameters5.Add("@src_locate_name", oldStock[0].LocateName);
                updateStringparameters5.Add("@dest_locate_id", oldStock[0].LocateId);
                updateStringparameters5.Add("@dest_locate_name", oldStock[0].LocateName);
                updateStringparameters5.Add("@old_qty", 0);
                updateStringparameters5.Add("@new_qty", splitNum);
                updateStringparameters5.Add("@trans_qty", oldStock[0].Qty);
                updateStringparameters5.Add("@old_status", oldStock[0].Status);
                updateStringparameters5.Add("@new_status", oldStock[0].Status);
                updateStringparameters5.Add("@old_qms_status", oldStock[0].QmsStatus);
                updateStringparameters5.Add("@new_qms_status", oldStock[0].QmsStatus);
                updateStringparameters5.Add("@unit", oldStock[0].Unit);
                updateStringparameters5.Add("@factory_id", oldStock[0].FactoryId);
                updateStringparameters5.Add("@factory_code", oldStock[0].FactoryCode);
                updateStringparameters5.Add("@src_erp_warehouse", oldStock[0].ErpWarehouse);
                updateStringparameters5.Add("@dest_erp_warehouse", oldStock[0].ErpWarehouse);
                updateStringparameters5.Add("@src_warehouse_id", oldStock[0].WarehouseId);
                updateStringparameters5.Add("@src_warehouse_name", oldStock[0].WarehouseName);
                updateStringparameters5.Add("@dest_warehouse_id", oldStock[0].WarehouseId);
                updateStringparameters5.Add("@dest_warehouse_name", oldStock[0].WarehouseName);
                updateStringparameters5.Add("@src_zone_id", oldStock[0].ZoneId);
                updateStringparameters5.Add("@src_zone_name", oldStock[0].ZoneName);
                updateStringparameters5.Add("@dest_zone_id", oldStock[0].ZoneId);
                updateStringparameters5.Add("@dest_zone_name", oldStock[0].ZoneName);
                updateStringparameters5.Add("@enabled", oldStock[0].Enabled);
                updateStringparameters5.Add("@update_userid", loginId);
                updateStringparameters5.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters5.Add("@create_userid", loginId);
                updateStringparameters5.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters5.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(updateString5.ToString());
                parameterList.Add(updateStringparameters5);
                #endregion

                
                //新增wms_rack_package
                #region  wms_rack_package
                DynamicParameters parameters = new DynamicParameters();
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("INSERT INTO dbo.wms_rack_package (rack_no,corton_no,packageType,part_no,");
                sql.Append(" rack_num,factory_id,factory_code,enabled,create_userid,create_time)");
                sql.Append("VALUES (@rackNo,@cortonNo,@packageType,@partNo,@rackNum,@factoryId,");
                sql.Append(" @factoryCode,@enabled,@createUserid,@createTime)");

                sqlStrings.Add(sql.ToString());
                string result = string.Empty;

                //if (pack == false && string.IsNullOrEmpty(rackNo))
                //{
                //    string rackNos = GetOrderNo("shipping_tp", "TP");
                //    parameters.Add("@rackNo", rackNos);
                //    result = rackNos;
                //}
                //if (pack == false && !string.IsNullOrEmpty(rackNo))
                //{
                //    parameters.Add("@rackNo", rackNo);
                //    result = rackNo;
                //}
                //if (pack == true)
                //{
                //    string rackNos = GetOrderNo("shipping_tp", "TP");
                //    parameters.Add("@rackNo", rackNos);
                //    result = rackNos;
                //}
                parameters.Add("@rackNo", "");
                parameters.Add("@cortonNo", oldStock[0].CartonNo);
                parameters.Add("@packageType", 2);
                parameters.Add("@partNo", oldStock[0].PartNo);
                parameters.Add("@rackNum", oldStock[0].Qty);
                parameters.Add("@factoryId", oldStock[0].FactoryId);
                parameters.Add("@factoryCode", oldStock[0].FactoryCode);
                parameters.Add("@enabled", 'Y');
                parameters.Add("@createUserid", loginId);
                parameters.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                
                parameterList.Add(parameters);
                #endregion

                //新增发运记录
                #region  shipping_log
                DynamicParameters dynamics = new DynamicParameters();
                //获取物流公司信息
                //StringBuilder stringBuilder = new StringBuilder(1024);
                //stringBuilder.Append($"SELECT * FROM dbo.wms_outstock WHERE order_no='{shippingNo}'");
                //List<WmsOutstock_Extend> wmsOutstocks = dbConn.Query<WmsOutstock_Extend>(stringBuilder.ToString()).ToList();

                StringBuilder builder1 = new StringBuilder();
                builder1.Append("INSERT INTO dbo.sys_shipping_log (shipping_no,part_no,rack_no,carton_no,");
                builder1.Append(" qty,logistics_code,box_weight,all_cost,shipping_type,");
                builder1.Append(" factory_id,factory_code,enabled,create_userid,create_time)");
                builder1.Append("VALUES (@shippingNo,@partNo,@rackNo,@cartonNo,");
                builder1.Append(" @qty,@logisticsCode,@boxWeight,@allCost,@shippingType,");
                builder1.Append(" @factoryId,@factoryCode,@enabled,@createUserid,@createTime)");

                sqlStrings.Add(builder1.ToString());

                dynamics.Add("@shippingNo", shippingNo);
                dynamics.Add("@partNo", oldStock[0].PartNo);
                dynamics.Add("@qty", oldStock[0].Qty);
                dynamics.Add("@rackNo", "");
                dynamics.Add("@cartonNo", oldStock[0].CartonNo);
                dynamics.Add("@logisticsCode", wmsOutstocks.FirstOrDefault().LogisticsCompany);
                dynamics.Add("@boxWeight", 0);
                dynamics.Add("@allCost", 0);
                dynamics.Add("@shippingType", 1);
                dynamics.Add("@factoryId", oldStock[0].FactoryId);
                dynamics.Add("@factoryCode", oldStock[0].FactoryCode);
                dynamics.Add("@enabled", 'Y');
                dynamics.Add("@createUserid", loginId);
                dynamics.Add("@createTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                parameterList.Add(dynamics);


                #endregion

                //修改发运明细
                #region
                StringBuilder string1= new StringBuilder(1024);
                string1.Append($"SELECT * FROM dbo.wms_outstock_detail WHERE order_no='{shippingNo}' and part_no='{oldStock[0].PartNo}' AND enabled='Y'");
                List<WmsOutstockDetail> details = dbConn.Query<WmsOutstockDetail>(string1.ToString()).ToList();

                if (details.FirstOrDefault().Qty == details.FirstOrDefault().OutQty + oldStock[0].Qty)
                {
                    StringBuilder stringBuilder1 = new StringBuilder(1024);
                    stringBuilder1.Append($"UPDATE dbo.wms_outstock_detail set item_status=40,out_qty=out_qty+@outQty,update_userid=@update_userid,update_time=@update_time WHERE order_no=@order_no AND part_no=@partNo");
                    sqlStrings.Add(stringBuilder1.ToString());

                    DynamicParameters parameters1 = new DynamicParameters();
                    parameters1.Add("@outQty", oldStock[0].Qty);
                    parameters1.Add("@update_userid", loginId);
                    parameters1.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    parameters1.Add("@order_no", shippingNo);
                    parameters1.Add("@partNo", oldStock[0].PartNo);
                    parameterList.Add(parameters1);
                }
                if (details.FirstOrDefault().Qty > details.FirstOrDefault().OutQty + oldStock[0].Qty)
                {
                    StringBuilder stringBuilder1 = new StringBuilder(1024);
                    stringBuilder1.Append($"UPDATE dbo.wms_outstock_detail set out_qty=out_qty+@outQty,update_userid=@update_userid,update_time=@update_time WHERE order_no=@order_no AND part_no=@partNo");
                    sqlStrings.Add(stringBuilder1.ToString());

                    DynamicParameters parameters1 = new DynamicParameters();
                    parameters1.Add("@outQty", oldStock[0].Qty);
                    parameters1.Add("@update_userid", loginId);
                    parameters1.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    parameters1.Add("@order_no", shippingNo);
                    parameters1.Add("@partNo", oldStock[0].PartNo);
                    parameterList.Add(parameters1);
                }
                if (details.FirstOrDefault().Qty < details.FirstOrDefault().OutQty + oldStock[0].Qty)
                {
                    return new List<SysStock>();
                }
                
                #endregion

                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();

                bool successCount = true;
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                    {
                        successCount = false;
                    }
                }
                if (successCount)
                {
                    transaction.Commit();
                    return oldStock;
                }
                else
                {
                    transaction.Rollback();
                    return null;
                }
            }
        }

        public string checkCartonNo(string carton, int splitCount)
        {
            List<SysStock> MaterialInfo = GetMaterialInfo(carton + "-" + splitCount);
            if (MaterialInfo.Count > 0)
            {
                //有重复
                return checkCartonNo(carton, splitCount + 1);
            }
            else
            {
                return carton + "-" + splitCount;
            }
        }
        /// <summary>
        /// 获取箱条码信息
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <returns></returns>
        public List<SysStock> GetMaterialInfo(string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                string result = string.Empty;

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from sys_stock (nolock) where enabled=@enabled and  carton_no= @carton_no or part_spec=@carton_no ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@enabled", 'Y');
                parameters.Add("@carton_no", cartonNo);

                return dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();
            }
        }

        
        public int UpdateOutStockDetail(string shippingNo, string cartonNo,int loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder builder= new StringBuilder();
                builder.Append($"SELECT * FROM dbo.sys_stock (nolock) WHERE carton_no='{cartonNo}' AND enabled='Y'");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(builder.ToString()).ToList();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"UPDATE dbo.wms_outstock_detail SET item_status=30,update_userid={loginId},update_time=GETDATE() WHERE order_no='{shippingNo}' AND part_no='{sysStocks.FirstOrDefault().PartNo}' AND enabled='Y'");


                return dbConn.Execute(sql.ToString());
            }
        }

        public int UpdateShippingLog(string shippingNo, string weight, string loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder builder = new StringBuilder();
                builder.Append($"SELECT * FROM dbo.wms_outstock (nolock) a  INNER JOIN dbo.wms_logisticsinfo b ON a.LogisticsCompany=b.logisticscode WHERE a.enabled='Y' and b.enabled='Y'");
                List<WmsLogisticsinfo> logisticsinfos = dbConn.Query<WmsLogisticsinfo>(builder.ToString()).ToList();

                #region  计算运费
                var rule = logisticsinfos.FirstOrDefault().Pricingrule.Split('+');
                decimal cost = 0;
                decimal price = 0;
                foreach (var item in rule)
                {
                    if (!item.Contains("*"))
                    {
                        cost +=decimal.Parse( item);
                    }
                    else
                    {
                        var rules= item.Split('*');
                        for (int i = 0; i < rules.Length; i++)
                        {
                            if (!rules[i].Contains("x"))
                            {
                                price = decimal.Parse(weight) *decimal.Parse( rules[i]);
                            }
                        }
                        cost += price;
                    }
                }
                #endregion

                StringBuilder stringBuilder= new StringBuilder();
                stringBuilder.Append($"SELECT * FROM dbo.sys_shipping_log (nolock) WHERE shipping_no='{shippingNo}' and rack_no='' AND enabled='Y' AND shipping_type=1");
                List<SysShippingLog> shippingLogs=dbConn.Query<SysShippingLog>(stringBuilder.ToString()).ToList();
                
                
                string rackNos = GetOrderNo("shipping_tp", "TP");
                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"UPDATE dbo.sys_shipping_log SET rack_no='{rackNos}',box_weight={weight},all_cost={cost},update_userid={loginId},update_time=GETDATE() WHERE shipping_no='{shippingNo}' AND rack_no='' AND enabled='Y' AND shipping_type=1");
                dbConn.Execute(sql.ToString());

                //更新package表rack_no字段
                StringBuilder stringBuilder1 = new StringBuilder(1024);
                foreach (var item in shippingLogs)
                {
                    stringBuilder1.Append($"UPDATE dbo.wms_rack_package SET rack_no='{rackNos}',update_userid={loginId},update_time=GETDATE() WHERE corton_no='{item.CartonNo}' AND enabled='Y';");

                }
                dbConn.Execute(stringBuilder1.ToString());

                return 1;
            }
        }

        public int UpdateOutStock(string shippingNo, string loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"UPDATE dbo.wms_outstock SET order_status=40,update_userid={loginId},update_time=GETDATE() WHERE order_no='{shippingNo}' ");

                return dbConn.Execute(sql.ToString());
            }
        }

        public int GetDetailQty(string shippingNo, string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder stringBuilder= new StringBuilder(1024);
                stringBuilder.Append($"SELECT * FROM dbo.sys_stock (nolock) WHERE carton_no='{cartonNo}' AND enabled='Y'");
                List<SysStock> sysStocks = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"SELECT * FROM dbo.wms_outstock_detail (nolock) where order_no='{shippingNo}' and part_no='{sysStocks.FirstOrDefault().PartNo}' AND enabled='Y' ");
                List<WmsOutstockDetail> details = dbConn.Query<WmsOutstockDetail>(sql.ToString()).ToList();
                if (details.FirstOrDefault().Qty == details.FirstOrDefault().OutQty)
                {
                    return 1;
                }
                else
                {
                    return -1;
                }
            }
        }

        public List<SysShippingLog> GetShippingLogs(string shippingNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"SELECT * FROM dbo.sys_shipping_log (nolock) WHERE rack_no='' AND enabled='Y' AND shipping_type=1");

                return dbConn.Query<SysShippingLog>(sql.ToString()).ToList();
            }
        }

        public List<WmsOutstockDetail> GetOutstockDetails(string shippingNo, string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                StringBuilder sql = new StringBuilder(1024);
                sql.Append($"SELECT * FROM dbo.sys_stock (nolock) a INNER JOIN dbo.wms_outstock_detail (NOLOCK) b ON a.part_no=b.part_no WHERE a.carton_no='M232302210001-1' AND b.order_no='P222209280001' AND a.enabled='Y' AND b.enabled='Y' ");

                return dbConn.Query<WmsOutstockDetail>(sql.ToString()).ToList();
            }
        }
    }
}
